<?php


function foria_menu ($db, $parent_id = 0, $basename = "", $level = 0, $PATH)
{

	$data = array ();

	$db->where('parent_id', $parent_id);
	$db->where('in_menu', 'true');
	$db->where('active', 'true');
	$db->order_by('position');
	$db->select('name, mname');
	$query = $db->get('foria_pages');

	if ($query->num_rows()>0)
	{

		$t = "";
		if (isset($PATH[$level]))
		{
			for ($i = 0; $i <= $level; $i++)
			{
				if ($t != "") $t .= "/";
				$t .= $PATH[$i]['name'];
			}
		}

		foreach ($query->result_array() as $row)
		{
			$tname = $row['name'];
			if ($basename != "")
			{
				$tname = $basename ."/".$tname;
			}
			$t == $tname?$is_active=true:$is_active = false;
			$data [] = array ('name'=>$tname, 'mname'=>$row['mname']==""?$row['name']:$row['mname'], 'is_last'=>false, 'is_active'=>$is_active);
		}
	}

	if (count($data)>0)
	{
		$data[count($data)-1]['is_last']=true;
	}

	return $data;

}

function findParentByName(&$db, $name, $submenu = false)
{

	$parent_id = 0;
	$names = explode ('/', $name);
	$basename = "";
	$retnames = array();
	$i = 0;

	foreach ($names as $n)
	{
		$db->where('parent_id', $parent_id);
		$db->where('name', $n);
		$db->select('id, parent_id, name');
		$query = $db->get('foria_pages');
		if ($row = $query->result_array())
		{
			$retnames[] = $row[0]['name'];
			$parent_id = $row[0]['id'];
			$ret_id = $row[0]['parent_id'];
			$i ++;
		}
	}

	if ($submenu == true)
	{
		$ret_id = $parent_id;
	}
	else
	{
		unset($retnames[count($names)-1]);
	}

	return array (implode ('/', $retnames), $ret_id, $i);

}


function smarty_function_menu ($params, $template)
{

	$db = $template->getRegisteredObject('db');

	isset($params['submenu'])&&$params['submenu']==true?$submenu=true:$submenu=false;

	$basename = "";
	$parent_id = 0;
	$level = 0;

	if ($submenu == true)
		list ($basename, $parent_id, $level) = findParentByName ($db, $params['page'], $submenu);

	$PATH = $template->tpl_vars['PATH']->value;


	$data = foria_menu ($db, $parent_id, $basename, $level, $PATH);
	$template->assign('MENU', $data);

	return "";

}